package com.zhouyx.schedule;

import java.util.Date;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

/**
 * @ClassName TestTaskService
 * @Description
 * @Author za-zhouyunxing
 * @Date 2019/7/26 10:57
 * @Version 1.0
 */
@Lazy(false)
@Service
@EnableScheduling
public class TestTaskService implements SchedulingConfigurer {
    private static Logger log = LoggerFactory.getLogger(TestTaskService.class);

    private String SpringDynamicCronTask() {
        String cron = "0/5 * * * * ?";
        //从数据库获得配置的corn表达式
        cron = getCron();
        log.info(cron);
        return cron;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(new Task(), new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                String s = SpringDynamicCronTask();
                // 任务触发，可修改任务的执行周期
                CronTrigger trigger = new CronTrigger(s);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        });
    }

    /** 从数据库获取Corn表达式配置 */
    public String getCron() {
        Random random = new Random();
        int i = random.nextInt(10);
        log.info("i="+i);
        if (i < 5){
            return "0/12 * * * * ?";
        }
        return "0/20 * * * * ?";
    }
}
